from asset.models import Host
from celery import shared_task
from website.celeryCenter import app as celeryApp
from utils.sshops import SSH
import time
import json

from utils.custom_log  import log_start
logger = log_start('task')

@shared_task
def task_balance():
    pass

@shared_task
def task_host_collect(req,local_file=None,remote_file=None,ssh_ip=None):
    logger.info(f'获取views传入数据:{req} {remote_file} {ssh_ip}')
    
    ## 读取配置,远程执行
    hostname = req['hostname']
    server = Host.objects.get(hostname = hostname)
    if server.ssh_id.authentication_type == 'Text':
        with SSH(
                ssh_ip, 
                server.ssh_id.ssh_port, 
                server.ssh_id.ssh_user, 
                password=server.ssh_id.password) as ssh:
                ssh.sftp_put_file(local_file, remote_file)
                result = ssh.command('python %s' %remote_file)
    else:
        with SSH(
                ssh_ip, 
                server.ssh_id.ssh_port, 
                server.ssh_id.ssh_user, 
                key=server.ssh_id.private) as ssh:
                ssh.sftp_put_file(local_file, remote_file)
                result = ssh.command('python %s' %remote_file)

    ## 更新配置到数据库
    if result['code'] == 200:
        data = json.loads(result['data'])
        # data['is_verified'] = 'verified'
        Host.objects.filter(hostname=hostname).update(**data)
        result = "ok"
    else:
        result = 'ssh执行返回异常'
    time.sleep(30) 
    return result 
    
  



    
 

    